#pragma once

//实现服务 计算器
#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

class ServerCalcu
{
public:
    ServerCalcu() {}
    ~ServerCalcu() {}

    //传入请求 计算结果
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = (req.x + req.y);
            break;
        case '-':
            resp.result = (req.x - req.y);
            break;
        case '*':
            resp.result = (req.x * req.y);
            break;
        case '/':
        {
            if (req.y == 0)
                resp.code = Div_Zero;
            else
                resp.result = (req.x / req.y);
        }
        break;
        case '%':
        {
            if (req.y == 0)
                resp.code = Mod_Zero;
            else
                resp.result = (req.x % req.y);
        }
        break;
        default:
            resp.code = Other_Oper;
            break;
        }

        return resp;
    }

    // "len"\n"10 + 20"\n   发过来 对其解析 并且在序列化 准备发送回去给客户端
    std::string Calculator(std::string& package)
    {
        std::string contect;
        bool r = Decode(package, &contect);
        if(!r)
            return ""; //解析失败
        
        Request req;
        r = req.Deserialize(contect);  //"10 + 20" --> x=10  op = '+'   y=20
        if(!r)
            return ""; //解析失败

        contect = "";
        Response resp = CalculatorHelper(req); //result=30 code=0;
        
        r = resp.Serialize(&contect); //"30"
        if(!r)
            return ""; //序列化失败
        
        contect = Encode(contect);

        return contect;
    }
    
};
